package com.koalacloud.koala.zhaikucloud.util;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.cat.indices.IndicesRecord;
import co.elastic.clients.elasticsearch.indices.CreateIndexResponse;
import co.elastic.clients.elasticsearch.indices.DeleteIndexResponse;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: GuoYang
 * @Description
 * @create 2022-05-18
 */
@Service
@RequiredArgsConstructor
public class EsIndexOperation {

    private final ElasticsearchClient client;

    /**
     * 判断索引是否存在
     * @param indexName
     * @return
     */
    public boolean checkIndex(String indexName) {
        try {
//            client.indices().get(g -> g.index(indexName));
            BooleanResponse booleanResponse = client.indices().exists(e -> e.index(indexName));
            return booleanResponse.value();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 创建索引
     */
    public boolean createIndex(String indexName) {
        try {
            if(!checkIndex(indexName)){
                CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index(indexName.toLowerCase()));
                return createIndexResponse.acknowledged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除索引
     */
    public boolean deleteIndex(String indexName) {
        try {
            if(checkIndex(indexName)){
                DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index(indexName.toLowerCase()));
                return deleteIndexResponse.acknowledged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询全部索引
     * @return
     * @throws IOException
     */
    public List<String> indexAll() throws IOException {
        List<IndicesRecord> indices = client.cat().indices().valueBody();
        return indices.stream().map(IndicesRecord::index).collect(Collectors.toList());
    }
}
